package com.gzhryc.net_marketing.api;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.config.*;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

/**
 * 配置API服务
 */
public class ConfigAPIService {

    private static Logger log = Logger.getLogger(ConfigAPIService.class);

    private static ConfigAPIService me;

    public static ConfigAPIService self(){
        if(me == null) {
            me = new ConfigAPIService();
        }
        return me;
    }

    private CloseableHttpClient httpClient;
    private String cloudApiHttpDomain;

    public void initial(String cloudApiHttpDomain) {
        this.cloudApiHttpDomain = cloudApiHttpDomain;
        this.httpClient = HttpClients.createDefault();
    }

    public MarketProjectAppConfigResponse getMarketProjectAppConfig(String token) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/project/config.data").build();

            MarketProjectAppConfigRequest apiReq = new MarketProjectAppConfigRequest();
            apiReq.getBody().setToken(token);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取网销运营商应用配置信息返回：" + str);
                if(JsonTools.isJsonStr(str)) {
                    MarketProjectAppConfigResponse apiResp = JsonTools.fromJson(str, MarketProjectAppConfigResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取网销运营商应用配置信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    
    public MarketSupplierConfigResponse getMarketSupplierConfig(String token) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/supplier/config.data").build();

            MarketSupplierConfigRequest apiReq = new MarketSupplierConfigRequest();
            apiReq.getBody().setToken(token);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取网销运营商应用配置信息返回：" + str);
                if(JsonTools.isJsonStr(str)) {
                	MarketSupplierConfigResponse apiResp = JsonTools.fromJson(str, MarketSupplierConfigResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取网销运营商应用配置信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public LogisticsCompanyListResponse findLogisticsCompanyList(String name, Integer pageNo, Integer pageLimit) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/logistics/company/list.data").build();

            LogisticsCompanyListRequest apiReq = new LogisticsCompanyListRequest();
            apiReq.getBody().setName(name);
            apiReq.getBody().setPageNo(pageNo);
            apiReq.getBody().setPageLimit(pageLimit);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取物流公司信息返回：" + str);
                if(StringTools.isNotBlank(str)) {
                    LogisticsCompanyListResponse apiResp = JsonTools.fromJson(str, LogisticsCompanyListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取物流公司信息错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public LogisticsCostListResponse findLogisticsCostList(LogisticsCostListRequest apiReq) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/logistics/cost/list.data").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取物流收费列表信息返回：" + str);
                if(StringTools.isNotBlank(str)) {
                    LogisticsCostListResponse apiResp = JsonTools.fromJson(str, LogisticsCostListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取物流收费列表信息错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public LogisticsUsableCostResponse getLogisticsUsableCostList(LogisticsUsableCostRequest apiReq) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/logistics/cost/usable.data").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取可用物流收费返回：" + str);
                if(StringTools.isNotBlank(str)) {
                    LogisticsUsableCostResponse apiResp = JsonTools.fromJson(str, LogisticsUsableCostResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取可用物流收费错误，" + e.getMessage(), e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
